package cn.s1995.sloth.pay.biz.handler.impl;

import cn.hutool.json.JSONUtil;
import cn.s1995.sloth.pay.entity.PayNotifyRecord;
import cn.s1995.sloth.pay.biz.handler.BizPayNotifyCallbackHandler;
import cn.s1995.sloth.pay.service.PayNotifyRecordService;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * AbstractBizPayNotifyCallbackHandler
 *
 * @author Lex
 * @description
 * @date 2024/01/06 01:21
 */
@Slf4j
public abstract class AbstractBizPayNotifyCallbackHandler implements BizPayNotifyCallbackHandler {

    /**
     * 调用入口
     * @param params
     * @return
     */
    @Override
    public String handle(Map<String, Object> params) {

        // 初始化租户
        before(params);

        // 去重处理
        if (duplicateChecker(params)) {
            return null;
        }

        // 验签处理
        if (!verifyNotify(params)) {
            return null;
        }

        String result = parse(params);
        // 保存处理结果
        saveNotifyRecord(params, result);
        return result;
    }


    /**
     * 保存记录
     * @param params
     * @param result
     * @param record
     * @param notifyId
     * @param recordService
     */
    void saveRecord(Map<String, Object> params, String result, PayNotifyRecord record, String notifyId,
                    PayNotifyRecordService recordService) {
        record.setNotifyId(notifyId);
        record.setOrderNo(notifyId);
        record.setRequest(JSONUtil.toJsonStr(params));
        record.setResponse(result);
        recordService.save(record);
    }

}
